#!/usr/bin/env bash

set -e # exit when error

# When running through yarn, this variable is changed, preventing the publishing
# to actually work. We revert it to its default value.
export npm_config_registry='https://registry.npmjs.org/'

if ! npm owner ls | grep -q "$(npm whoami)"
then
  echo "Release: Not an owner of the npm repo, ask for it"
  exit 1
fi

currentBranch=$(git rev-parse --abbrev-ref HEAD)
if [ "$currentBranch" != 'master' ]; then
  echo "Release: You must be on master"
  exit 1
fi

if [[ -n $(git status --porcelain) ]]; then
  echo "Release: Working tree is not clean (git status)"
  exit 1
fi

echo
echo "Release: update working tree"
git pull origin master
git fetch origin --tags

echo "Release: yarn install"
yarn install

currentVersion=$(json version < package.json)

# header
echo ""
echo "Release: current version is $currentVersion"
echo "Release: a changelog will be generated only if a fix/feat/performance/breaking token is found in git log"
echo "Release: you must choose a new ve.rs.ion (semver)"
echo "Release: press q to exit the next screen"
echo ""
echo ""


# preview changelog
read -rp "=> Release: press [ENTER] to view changes since latest version.."

conventional-changelog --preset angular --output-unreleased | less

# choose and bump new version
echo "=> Release: please type the new chosen version > "
read -re newVersion
VERSION=$newVersion babel-node ./scripts/bump-package-version.js

# build new version
NODE_ENV=production VERSION=$newVersion yarn run build

# update changelog
echo
echo "Release: update changelog"
changelog=$(conventional-changelog -p angular)
conventional-changelog --preset angular --infile CHANGELOG.md --same-file -r 0

# regenerate readme TOC
echo
echo "Release: generate TOCS"
yarn run doctoc

# git add and tag
commitMessage="v$newVersion\n\n$changelog"
git add src/lib/version.js package.json CHANGELOG.md README.md CONTRIBUTING.md
echo "$commitMessage" | git commit --file -
git tag "v$newVersion"

echo
echo "Release: almost done, check everything in another terminal tab."
read -rp "=> Release: when ready, press [ENTER] to push to github and publish the package"

echo
echo "Release: push to github, publish on npm"
git push origin master
git push origin --tags
npm publish

echo "Release: Package was published to npm."
